import 'dart:async';
import 'dart:convert';
import 'dart:math' as Math;

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter_wear_app/utils/http_util.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationService {
  StreamSubscription<Map<String, Object>>? _locationListener;
  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();
  PermissionStatus? status;
  Point? oldPoint;

  Future<void> run(void Function(Map<String, dynamic>) callback) async {
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey(
      "6cc2ba709e7811a8cd9e90cf4a98c7ff",
      "ios ApiKey", // 建议也设置有效的iOS Key
    );
    // 新增：确保只监听一次
    if (_locationListener != null) {
      await _locationListener?.cancel();
      _locationListener = null;
    }

    bool isPermitted = await _requestPermission();
    print("是否授权：$isPermitted");

    if (isPermitted) {
      _locationListener = _locationPlugin.onLocationChanged().listen((
        result,
      ) async {
        print(jsonEncode(result));
        if (result['address'] == null) {
          return;
        }
        if (oldPoint == null) {
          // 将 result['latitude'] 和 result['longitude'] 转换为 double 类型
          oldPoint = Point(
            latitude: double.parse(result['latitude'].toString()),
            longitude: double.parse(result['longitude'].toString()),
          );
        } else {
          Point nowPoint = Point(
            latitude: double.parse(result['latitude'].toString()),
            longitude: double.parse(result['longitude'].toString()),
          );

          final distance = DistanceCalculator().calculateDistance(
            oldPoint!,
            nowPoint,
          );
          if (distance >= 20 && result['address'] != '') {
            oldPoint = nowPoint;
            await _uploadLocation(result);
          }
        }
        callback(result);
        print("经纬度：${result['longitude']},${result['latitude']}");
        print("定位结果：$result");
      });
      _startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption(
      onceLocation: false,
      needAddress: true,
      locationInterval: 10000,
    );

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }

  ///开始定位
  void _startLocation() {
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///停止定位
  void _stopLocation() {
    _locationPlugin.stopLocation();
  }

  void cancel() {
    if (_locationListener != null) {
      _locationListener?.cancel();
      _locationListener = null; // 增加置空操作
      _stopLocation(); // 确保停止定位
    }
  }

  Future<void> _uploadLocation(Map<String, dynamic> addresInfo) async {
    final res = await HttpUtil.post(
      '/trace/create',
      params: {
        "longitude": addresInfo['longitude'],
        "latitude": addresInfo['latitude'],
        "address": addresInfo['address'],
      },
    );

    if (res['code'] == 1) {
      print(res['data']);
    } else {
      print(res['msg']);
    }
  }

  /// 动态申请定位权限
  Future<bool> _requestPermission() async {
    var status = await _requestLocationPermission();
    var backgroundStatus = await _requestBackgroundLocationPermission();
    if (status && backgroundStatus) {
      return true;
    } else {
      return false;
    }
  }

  Future<bool> _requestLocationPermission() async {
    var status = await Permission.location.request();
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      return false;
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
      return false;
    }
    return false;
  }

  Future<bool> _requestBackgroundLocationPermission() async {
    try {
      if (await Permission.locationAlways.request().isGranted) {
        return true;
      }
      openAppSettings();
      return false;
    } catch (e) {
      print("Error requesting background location permission: $e");
      return false;
    }
  }
}

class DistanceCalculator {
  // 地球半径，单位：米
  static const double R = 6371000;

  // 角度转弧度
  double deg2rad(double deg) {
    return deg * (3.1415926535897932 / 180);
  }

  // 计算两点间的距离
  double calculateDistance(Point pta, Point ptb) {
    final double lat1 = deg2rad(pta.latitude);
    final double lat2 = deg2rad(ptb.latitude);
    final double dLat = deg2rad(ptb.latitude - pta.latitude);
    final double dLon = deg2rad(ptb.longitude - pta.longitude);

    final double a =
        (Math.sin(dLat / 2) * Math.sin(dLat / 2)) +
        (Math.cos(lat1) *
            Math.cos(lat2) *
            Math.sin(dLon / 2) *
            Math.sin(dLon / 2));
    final double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  }
}

class Point {
  final double latitude;
  final double longitude;

  Point({required this.latitude, required this.longitude});
}
